/*
  Copyright 1996-2003
  Simon Whiteside

*/
package simkin.examples.inherits;
import simkin.*;
import org.w3c.dom.*;
import org.apache.crimson.tree.*;
import org.xml.sax.*;
import java.io.*;

/** 
 * this class extends the XMLElementObject class with understanding of the &lt;inherits&gt; tag. It overrides the createXMLElementObject method to make sure that any sub-elements are also checked.
 */
public class InheritsElement extends XMLElementObject {
    /** Constructor - passes element up to its parent */
    public InheritsElement(String location,Element elem){
	super(location,elem);
    }
    /** overrides this method so that sub-elements also understand the inherits tag */
    protected XMLElementObject createXMLElementObject(String location,Element element){
	return new InheritsElement(location,element);
    }
    /** extends this method to check for inherits tags after the element has been set */
    protected void setElement(Element elem){
	super.setElement(elem);
	if (elem!=null)
	    replaceInherits(elem);
    }
    /** this method replaces any &lt;inherits&gt; tags with the equivalent XML file */
    public static void replaceInherits(Element elem){
	NodeList nodes=elem.getChildNodes();
	int count=0;
	Document owner=elem.getOwnerDocument();
	for (int i=0;i<nodes.getLength();i++){
	    Node node=nodes.item(i);
	    if (node.getNodeType()==Node.ELEMENT_NODE){
		if (node.getNodeName().equals("inherits")){
		    try{
			// the data within the inherits tag is the the file name to import
			String file_name=getData((Element)node);
			XmlDocument doc=XmlDocument.createXmlDocument(new InputSource(new FileInputStream(file_name)),false);
			Element parent=doc.getDocumentElement();
			// check if this element has any inherits tags
			replaceInherits(parent);
			NodeList parent_nodes=parent.getChildNodes();
			for (int j=0;j<parent_nodes.getLength();j++){
			    elem.insertBefore(owner.importNode(parent_nodes.item(j),true),node);
			}
			elem.removeChild(node);
			i--;
		    }catch(Exception e ){
			Tracer.trace(e);
		    }
		}
	    }
	}
    }
}
